import { login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    role: '',
    mobile: '',
    username: '',
    id: null
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ROLE: (state, role) => {
    state.role = role
  },
  SET_MOBILE: (state, mobile) => {
    state.mobile = mobile
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_ID: (state, id) => {
    state.id = id
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        console.log(response)
        if (response.code === 200) {
          localStorage.setItem('userInfo',JSON.stringify(data.user))
          commit('SET_TOKEN', data.token)
          commit('SET_ROLE', data.user.role)
          commit('SET_MOBILE', data.user.mobile)
          commit('SET_USERNAME', data.user.username)
          commit('SET_ID', data.user.id)
          setToken(data.token)
          sessionStorage.setItem('token',data.token)
        }
        resolve(data)
      })
    })
  },
  clear({ commit }) {
    commit('RESET_STATE')
    localStorage.removeItem('userInfo')
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

